using System;
using System.Collections.Generic;
using Runtime.Common.Object;
using Runtime.Common.Interface;

namespace Runtime.DesignPattern
{
    /// <summary>
    ///     组合模式实现类
    /// </summary>
    public class Composite : IComposite
    {
        public List<IComposite> list { get; } = new();
        public IGuidObject Id { get; } = new GuidObject();

        public void AddChild(IComposite number)
        {
            list.Add(number);
        }

        public void RemoveChild(IComposite number)
        {
            list.Remove(number);
        }


        public List<V> GetNumbers<V>() where V : IComposite
        {
            return list.ConvertAll(value => (V)value);
        }

        public List<IComposite> GetNumbers()
        {
            return list;
        }

        public void Foreach(Action<IComposite> match)
        {
            foreach (var value in list) match?.Invoke(value);
        }

        /// <summary>
        ///     递归遍历所有子组合对象
        /// </summary>
        /// <param name="match"></param>
        public void ForeachByRecursion(Action<IComposite> match)
        {
            if (match == null) return;
            foreach (var value in list)
            {
                match.Invoke(value);
                value.ForeachByRecursion(match);
            }
        }

        public V Find<V>(Func<IComposite, bool> fun) where V : IComposite
        {
            foreach (var value in list)
                if (fun.Invoke(value))
                    return (V)value;

            return default;
        }

        public void Clear()
        {
            list.Clear();
            ;
        }
    }
}